// src/middlewares/validation.ts
import { Request, Response, NextFunction } from "express";
import { ValidationError } from "../../framework/utils/AppError";

export const validateUserCreate = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { name, email } = req.body;

  // 检查必填字段
  if (!name || !email) {
    return next(new ValidationError("姓名和邮箱是必填字段"));
  }

  // 验证姓名格式
  if (typeof name !== "string" || name.trim().length < 2) {
    return next(
      new ValidationError("姓名长度至少为2个字符", {
        field: "name",
        requirement: "至少2个字符",
      })
    );
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return next(
      new ValidationError("邮箱格式不正确", {
        field: "email",
        requirement: "请输入有效的邮箱格式",
        value: email,
      })
    );
  }

  next();
};

export const validateObjectId = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { id } = req.params;

  // 简单的ID格式验证（可以根据实际需求调整）
  if (!id || id.length < 12) {
    return next(
      new ValidationError("无效的ID格式", {
        field: "id",
        value: id,
        requirement: "有效的ID格式",
      })
    );
  }

  next();
};
